package com.xone.xapp;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class ProductUpdateActivity extends BasicImageOptActivity {
	protected final String TAG = ProductUpdateActivity.class.getSimpleName();
	protected Map<String, String> infoMap = new LinkedHashMap<String, String>();
	protected Spinner spinnerProductTypeName;
    protected LinearLayout outerView;
    protected String saleType;
    protected String id;
    protected List<String> imageIdList;
    protected String title;
	protected List<String> productTypeList = new ArrayList<String>();
	@Override
	public String getHeaderTitle() {
		return title;
	}
	@Override
	public int getContentView() {
		return R.layout.product_update;
	}
	@Override
	public Context getContext() {
		return this;
	}
	@Override
	public LinearLayout getOuterView() {
		return outerView;
	}
	@Override
	public String getImagesTag() {
		return "IMAGES_TAG";
	}
	@Override
	public String getPostUrl() {
		return "/product/updateJson.html";
	}
	/**
	 * 提交完成后的回调
	 */
	@Override
	public void postFinish(JSONObject result) {
		if (null == result) {
			Toast.makeText(getContext(), "操作失败", Toast.LENGTH_SHORT).show();
			return;
		}
		String msg = "提交成功";
		JSONObject mapValue = JSONUtils.getJSONObjectForKey(result, "mapValue");
		if (mapValue.isNull("msg")) {
			Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
			this.finish();
			return;
		}
		msg = JSONUtils.getStringFromJSONObject(mapValue, "msg");
		Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
	}
	protected void onCreate(Bundle savedInstanceState) {
		Bundle bundle = this.getIntent().getExtras();
		super.onCreate(savedInstanceState);
		if (null != bundle) {
			saleType = bundle.getString("saleType");
			id = bundle.getString("id");
			if (StringUtils.isBlank(saleType) || StringUtils.isBlank(id)) {
				Toast.makeText(this, "无产品类型信息", Toast.LENGTH_SHORT).show();
				this.finish();
				return;
			}
		}
		if ("0".equals(saleType)) {
			title = "更新产品发布";
		} else if ("1".equals(saleType)) {
			title = "更新促销发布";
		} else if ("2".equals(saleType)) {
			title = "更新组团发布";
		}
		imageIdList = new ArrayList<String>();
		outerView = (LinearLayout)findViewById(R.id.product_update_details_zone);
		infoMap.put("productName", "产品名称不能为空");
		infoMap.put("productAddress", "产品产地不能为空");
		infoMap.put("productLocation", "产品属地不能为空");
		infoMap.put("productPrice", "产品价格不能为空");
		infoMap.put("productNum", "产品数量不能为空");
		infoMap.put("productDesc", "");
		spinnerProductTypeName = (Spinner)findViewById(R.id.productTypeName);
		productTypeList.add("冻品");
		productTypeList.add("干货");
		productTypeList.add("活鲜");
		productTypeList.add("水果");
		productTypeList.add("调料");
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, productTypeList);
		spinnerProductTypeName.setAdapter(adapter);
		TextView idView = (TextView)outerView.findViewById(R.id.id);
		idView.setText(id);
		showProgress();
		new InitDataTask(this, outerView, ContextUtils.getScreenWidth(this)).execute(id);
		Button submitProduct = (Button)findViewById(R.id.submit_product_update);
		submitProduct.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Map<String, String> value = checkAndGetValue(infoMap);
				if (value.isEmpty()) {
					return;
				}
				int images = 0;
				View [] imageViews = new View[3];
				for (int i = 0; i < outerView.getChildCount(); i++) {
					View tv = outerView.getChildAt(i);
					String tag = (String)tv.getTag();
					if (getImagesTag().equals(tag)) {
						imageViews[images] = tv;
						images ++;
					}
				}
				if (images == 0 && (null == imageIdList || imageIdList.size() == 0)) {
					notPass(null, "请选择至少一张图片");
					return;
				}
				showProgress();
				String productType = spinnerProductTypeName.getSelectedItem().toString();
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				for (Map.Entry<String, String> info : value.entrySet()) {
					params.add(new BasicNameValuePair("product." + info.getKey(), info.getValue()));
				}
				params.add(new BasicNameValuePair("product.id", id));
				params.add(new BasicNameValuePair("product.saleType", saleType));
				for (String imageId : imageIdList) {
					params.add(new BasicNameValuePair("product.ids", imageId));
				}
				params.add(new BasicNameValuePair("product.productType", String.valueOf(productTypeList.indexOf(productType))));
				new Base64Task(getContext(), params).execute(imageViews);
			}
		});
		Button selectImage = (Button)findViewById(R.id.button_select_image);
		selectImage.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				int images = getImageCount();
				if ((images + imageIdList.size()) >= 3) {
					Toast.makeText(getContext(), "最多只能选择三张图片", Toast.LENGTH_SHORT).show();
					return;
				}
				Intent intent = new Intent();
				/* 开启Pictures画面Type设定为image */  
                intent.setType("image/*");  
                /* 使用Intent.ACTION_GET_CONTENT这个Action */  
                intent.setAction(Intent.ACTION_GET_CONTENT);   
                /* 取得相片后返回本画面 */  
                startActivityForResult(intent, 1); //imageview_select_image
			}
		});
	}
	
	public class InitDataTask extends AsyncTask<String, Integer, JSONObject> {
		protected Context context;
		protected LinearLayout view;
		protected int imageWidth;
		protected ImageLoader imageLoader = null;
		public InitDataTask(Context context, LinearLayout view, int imageWidth) {
			this.context = context;
			this.imageWidth = imageWidth;
			this.view = view;
			imageLoader = new ImageLoader(context, imageWidth * 2);
		}
		@Override
		protected JSONObject doInBackground(final String... params) {
			if (isCancelled()) {
				return null;
			}
			List<NameValuePair> reqparams = new ArrayList<NameValuePair>();
			reqparams.add(new BasicNameValuePair("product.id", params[0]));
			return HttpUtils.httpGet(Constants.APP_URL + "/product/itemJsonDetails.html", reqparams, 
					new HttpUtils.onGetSuccessListener<JSONObject>() {
						@Override
						public JSONObject onSuccess(int status, String result) {
							if (HttpUtils.SC_OK == status) {
								JSONObject jsonObject = JSONUtils.getJSONObjectFromString(result);
								JSONObject product = JSONUtils.getJSONObjectForKey(jsonObject, "product");
								return product;
							} else {
								Toast.makeText(context, "Status Code:" + status, Toast.LENGTH_SHORT).show();
							}
							return null;
						}
					}, context);
		}
		@Override
		protected void onPostExecute(JSONObject result) {
			super.onPostExecute(result);
			if (null == result) {
				hideProgress();
				return;
			}
			JSONObject product = result;
			int childCount = view.getChildCount();
			for (int i = 0 ; i < childCount; i++) {
				View v = view.getChildAt(i);
				String tag = (String)v.getTag();
				if (v instanceof LinearLayout && null != tag) {
					String value = null;
					if (!product.isNull(tag)) {
						value = JSONUtils.getStringFromJSONObject(product, tag);
					}
					if (null != value) {
						EditText tv = (EditText)view.findViewById(context.getResources().getIdentifier(tag, "id", context.getPackageName()));
						if (null != tv) {
							tv.setText(value);
						}
					}
				}
			}
			int position = productTypeList.indexOf(JSONUtils.getStringFromJSONObject(product, "productTypeName"));
			if (position < 0) {
				position = 0;
			}
			spinnerProductTypeName.setSelection(position);
			JSONArray ids = JSONUtils.getJSONArrayForKey(product, "ids");
			if (null != ids && ids.length() > 0) {
				for (int i = 0; i < ids.length(); i++) {
					String imgId = JSONUtils.getStringFromJSONArray(ids, i);
					imageIdList.add(imgId);
					final View mImageView = mInflater.inflate(R.layout.product_update_image, null);
					ImageView imageView = (ImageView)mImageView.findViewById(R.id.imageview_update_image);
					imageLoader.displayImage(Constants.APP_URL + "/assistant/image.html?id=" + imgId, imageView);
					imageView.getLayoutParams().height = imageWidth;
					Button deleteBtn = (Button)mImageView.findViewById(R.id.delete_image);
					deleteBtn.setTag(imgId);
					deleteBtn.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(final View v) {
							ContextUtils.confirm(getContext(), "确认删除该图片吗？", new android.content.DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									String imageId = (String)v.getTag();
									imageIdList.remove(imageId);
									view.removeView(mImageView);
								}
							});
						}
					});
					view.addView(mImageView, childCount - 2 + i);
				}
			}
			view.setVisibility(View.VISIBLE);
			hideProgress();
		}
	}

}
